import aiohttp
import asyncio
import json
from config import Config
from fastapi import HTTPException
import time
import logging
from typing import Optional, Dict, Any

async def call_dify_workflow(query: str, user_id: str, conversation_id: Optional[str] = None, inputs: Optional[Dict[str, Any]] = None, is_monitor: bool = False):
    """
    调用Dify对话消息API
    :param query: 用户查询内容
    :param user_id: 用户ID
    :param conversation_id: 对话ID，用于多轮对话，可选
    :param inputs: 额外输入参数，可选
    :param is_monitor: 是否为监控请求，监控请求会绕过缓存机制
    :return: 包含回答和会话ID的字典
    """
    start_time = time.time()
    
    # 如果是监控请求，添加特殊标识到查询中，确保每次都是真实调用
    if is_monitor:
        monitor_tag = f"[MONITOR_{int(time.time())}]"
        query = f"{monitor_tag} {query}"
        logging.info(f"[步骤2-Dify服务调用] 监控模式调用Dify服务，已添加监控标识")
    
    logging.info(f"[步骤2-Dify服务调用] 开始调用Dify服务")
    headers = {
        'Content-Type': 'application/json',
        'Authorization': f'Bearer {Config.DIFY_API_KEY}'
    }

    # 构建请求数据
    request_data = {
        'query': query,
        'response_mode': 'blocking',
        'user': user_id,
        'inputs': inputs or {}  # 如果未提供inputs，使用空字典
    }
    
    # 不再需要单独处理历史消息，因为历史消息已经拼接到用户查询中

    # 如果提供了conversation_id且不为空字符串，则添加到请求数据中
    if conversation_id and conversation_id.strip():
        request_data['conversation_id'] = conversation_id
    # 创建超时配置
    timeout = aiohttp.ClientTimeout(total=60)
    
    try:
        # 使用aiohttp发送异步POST请求
        async with aiohttp.ClientSession(timeout=timeout) as session:
            async with session.post(
                url=f'{Config.DIFY_API_URL}/chat-messages',
                headers=headers,
                data=json.dumps(request_data)
            ) as response:
                # 检查响应状态
                if response.status == 200:
                    result = await response.json()
                    # 提取回答
                    answer = result.get('answer', '未获取到回答')

                    # 不再返回Dify的conversation_id，而是返回我们自己管理的对话ID
                    end_time = time.time()
                    logging.info(f"[步骤2-Dify服务调用] 调用Dify服务耗时: {end_time - start_time:.2f}秒")
                    return {
                        'answer': answer,
                        'conversation_id': conversation_id  # 返回我们自己管理的对话ID
                    }
                else:
                    response_text = await response.text()
                    end_time = time.time()
                    logging.info(f"[步骤2-Dify服务调用] 调用Dify服务耗时: {end_time - start_time:.2f}秒")
                    return {
                        'answer': f'请求失败，状态码: {response.status}，响应: {response_text}',
                        'conversation_id': conversation_id
                    }
    except asyncio.TimeoutError as e:
        end_time = time.time()
        logging.error(f"[步骤2-Dify服务调用] Dify服务调用超时: {str(e)}, 耗时: {end_time - start_time:.2f}秒")
        return {
            'answer': '抱歉，服务响应超时，请稍后重试或联系管理员。',
            'conversation_id': conversation_id
        }
    except aiohttp.ClientError as e:
        end_time = time.time()
        logging.error(f"[步骤2-Dify服务调用] Dify服务请求异常: {str(e)}, 耗时: {end_time - start_time:.2f}秒")
        return {
            'answer': f'服务请求失败: {str(e)}',
            'conversation_id': conversation_id
        }
    except Exception as e:
        end_time = time.time()
        logging.error(f"[步骤2-Dify服务调用] Dify服务调用异常: {str(e)}, 耗时: {end_time - start_time:.2f}秒")
        return {
            'answer': f'请求异常: {str(e)}',
            'conversation_id': conversation_id
        }